#include "uart_parse.h"
#include "usart.h"
#include "flash.h"

#include "gl_parser.h"
#include "FreeRTOS.h"
#include "task.h"
#include "main.h"
#include "cmsis_os.h"

extern SemaphoreHandle_t xSemaphore;
PARSE_STRUCT parse_uart;
uint8_t is_recv = 0;
void send_uart_data(uint8_t *send_buffer, uint16_t send_len);

void printf_frame(FRAME_STRUCT *frame_s)
{
    // Log("Version:%02X ",frame_s->Version);
    // Log("FrameDataLen:%02X ",frame_s->FrameDataLen);
    // Log("SourceID:%02X ",frame_s->SourceID);
    // Log("TargetID:%02X ",frame_s->TargetID);
    // Log("Cmd:%02X ",frame_s->Cmd);
    // Log("DataIndex:%02X ",frame_s->DataIndex);
    // Log("Data:");
    // printf_byte(frame_s->frame_data,frame_s->FrameDataLen);
    // Log("\r\n");
}

void recv_uart_farme(void *arg)
{
    static BaseType_t xHigherPriorityTaskWoken;
    xSemaphoreGiveFromISR(xSemaphore, &xHigherPriorityTaskWoken);
}

void parse_loop(void)
{
    if (parse_uart.frame_s.MasterCmd == MASTER_CMD_SYSTEM)
    {
        parse_system_frame(&parse_uart);
    }
    else if (parse_uart.frame_s.MasterCmd == MASTER_CMD_FLASH)
    {
        parse_flash_frame(&parse_uart);
    }
}

void uart_receive_struct_init(void)
{
    parse_struct_init(&parse_uart);
    parse_set_rec_callback(&parse_uart, recv_uart_farme);
    parse_set_send_fun(&parse_uart, send_uart_data);

    send_version();
}

void receive_uart_data(uint8_t *receive_buffer, uint16_t receive_len)
{
    parse_data(&parse_uart, receive_buffer, receive_len);
}

void send_uart_data(uint8_t *send_buffer, uint16_t send_len)
{
    uart_transmit_buffer(send_buffer, send_len);
}

void send_version(void)
{
    unsigned char send_buf[3];
    FRAME_STRUCT frame_s;

    send_buf[0] = VERSION_1;
    send_buf[1] = VERSION_2;
    send_buf[2] = VERSION_3;

    frame_s.Version = PROTOCOL_VERSION;
    frame_s.FrameDataLen = 3;
    frame_s.MasterCmd = MASTER_CMD_SYSTEM;
    frame_s.SlaveCmd = SLAVE_CMD_SYSTEM_GET_VERSION_SUCCESS;
    frame_s.frame_data = send_buf;
    frame_s.send_frame_fun = send_uart_data;
    creat_send_cmd(&frame_s);
}
